<template>
  <div class="operate-panel">
    告警弹窗开关
    <el-switch :value="isAlarmPrompted" :width="30" style="margin-left: 20px" active-text="开启" inactive-text="关闭"
      @change="toggleSwitch">
    </el-switch>

    <audio id="audioPlay" src="static/119.ogg" controls="controls" style="display: none"></audio>
  </div>
</template>

<script>
import store from "@/store";

export default {
  name: "Operation",
  components: {},
  data() {
    return {
      alarmVisible: false,
      alarmCount: 0,
      mysocket: null,
      audio: null,
      audioSrc: "",
    };
  },
  computed: {
    username() {
      return this.$store.state.user.name;
    },
    isAlarmPrompted() {
      return store.getters.isAlarmPrompted;
    },
  },
  methods: {
    toggleSwitch(v) {
      this.$store.dispatch("setIsAlarmPrompted", v);
    },
    socketConn() {
      let socketUrl = window.location.host + process.env.VUE_APP_BASE_API;
      let self = this;
      // 重连
      function reconnect(url) {
        if (self.lockReconnect) return;
        self.lockReconnect = true;
        setTimeout(function () {
          //没连接上会一直重连，设置延迟避免请求过多
          createWebSocket(url);
          self.lockReconnect = false;
        }, 2000);
      }
      // 实例websocket
      function createWebSocket(url) {
        try {
          if ("WebSocket" in window) {
            self.mysocket = new WebSocket(url);
          } else if ("MozWebSocket" in window) {
            self.mysocket = new MozWebSocket(url);
          } else {
            self.$Message.error(
              "当前浏览器不支持websocket协议,建议使用现代浏览器",
              3000
            );
          }
          initEventHandle(url);
        } catch (e) {
          reconnect(url);
        }
      }
      let heartCheck = {
        timeout: 5 * 1000, //  心跳检测时长
        timeoutObj: null, // 定时变量
        reset: function () {
          // 重置定时
          clearTimeout(this.timeoutObj);
          return this;
        },
        start: function () {
          // 开启定时

          this.timeoutObj = setTimeout(function () {
            // 心跳时间内收不到消息，主动触发连接关闭，开始重连
            if (self.mysocket) {
              self.mysocket.send("heartbeat");
            }

            // self.mysocket.close();
          }, this.timeout);
        },
      };

      // 初始化事件函数
      function initEventHandle(wsUrl) {
        self.mysocket.onclose = function () {
          if (self.mysocket) {
            self.mysocket.close();
            console.log("Socket已关闭");
            reconnect(wsUrl);
          }
        };
        self.mysocket.onerror = function (err) {
          reconnect(wsUrl);
        };
        self.mysocket.onopen = function () {
          console.log("Socket 已打开");
          heartCheck.reset().start(); //心跳检测重置
        };
        self.mysocket.onmessage = function (msg) {
          //如果获取到消息，心跳检测重置
          heartCheck.reset().start(); //拿到任何消息都说明当前连接是正常的
          if (msg.data !== "heartbeat") {
            let alarmItem = JSON.parse(msg.data);
            console.log(msg);

            if (self.isAlarmPrompted) {
              // let audio = document.getElementById("audioPlay");
              // audio.play();
              //地图页面刷新一下更新 状态
              self.$emit("refreshMap");
              const h = self.$createElement;

              if (alarmItem.msgType == 1) {
                //垃圾桶告警
                self.$notify({
                  title: alarmItem.alarmMessage,
                  type: "warning",
                  position: "bottom-left",
                  duration: 30,
                  message: h("div", null, [
                    h("div", null, "设施名称: " + alarmItem.facilityName),
                    h(
                      "div",
                      { style: "color: red" },
                      "告警时间: " + alarmItem.dataTime
                    ),
                    h(
                      "el-button",
                      {
                        attrs: {},
                        props: {
                          type: "primary",
                          size: "mini",
                          plain: true,
                          icon: "el-icon-view",
                        },
                        style: {
                          marginTop: "5px",
                        },
                        on: {
                          click: () => {
                            self.$router.push({
                              name: "FacHistory",
                              params: {
                                facilityName: alarmItem.facilityName,
                              },
                            });
                          },
                        },
                      },
                      "查看告警详情"
                    ),
                    h(
                      "el-button",
                      {
                        attrs: {},
                        props: {
                          type: "primary",
                          size: "mini",
                          plain: true,
                          icon: "el-icon-location-information",
                        },
                        style: {
                          marginTop: "5px",
                        },
                        on: {
                          click: () => {
                            self.$emit("showMarker", alarmItem.deviceId);
                          },
                        },
                      },
                      "显示位置"
                    ),
                  ]),
                });
              }
            }
          }
        };
      }

      createWebSocket(`ws://${socketUrl}/ws/${this.username + Math.random()}`);
    },

    test() {
      let self = this;
      const h = this.$createElement;
      this.$notify({
        title: "始发地停留告警",
        type: "warning",
        message: h("div", null, [
          h("div", null, "派送单号: 1000000039563427 "),
          h("div", { style: "color: teal" }, "告警时间: 2020-10-29 12:47:35"),
          h(
            "el-button",
            {
              attrs: {},
              props: {
                type: "primary",
                size: "mini",
                plain: true,
                icon: "el-icon-location-information",
              },
              style: {
                marginTop: "5px",
              },
              on: {
                click: () => {
                  this.$router.push({
                    name: "FacHistory",
                    params: {
                      facilityName: "9号垃圾桶",
                    },
                  });
                },
              },
            },
            "查看告警详情"
          ),
          h(
            "el-button",
            {
              attrs: {},
              props: {
                type: "primary",
                size: "mini",
                plain: true,
              },
              style: {
                marginTop: "5px",
              },
              on: {
                click: () => {
                  self.$emit("showMarker", alarmItem.deviceId);
                },
              },
            },
            "显示位置"
          ),
        ]),
      });
    },
  },
  created() {
    // this.socketConn();
  },
  mounted() {
    // this.test();
  },
  beforeDestroy() {
    if (this.mysocket) {
      this.mysocket.close();
    }
  },
  beforeRouteLeave(to, from, next) {
    if (this.mysocket) {
      this.mysocket.close();
    }
  },
};
</script>

<style lang="scss" scoped>
.operate-panel {
  position: absolute;
  right: 10px;
  top: 15px;
  display: flex;
  align-items: center;

  .btn {
    border: none;
    background: transparent;
    font-size: 24px;
    padding: 2px 0px;
    color: #eee;
  }
}
</style>
